package com.wzt.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wzt.gift.asserts.Assert;
import com.wzt.gift.client.SmsVerifyCodeSendClient;
import com.wzt.gift.clients.LoginUserClient;
import com.wzt.gift.domain.LoginUser;
import com.wzt.gift.domain.User;
import com.wzt.gift.dto.SmsRegisterDto;
import com.wzt.gift.enums.ResponseEnum;
import com.wzt.gift.mapper.UserMapper;
import com.wzt.gift.service.IUserService;
import com.wzt.gift.util.AjaxResult;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author wzt
 * @since 2022-10-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SmsVerifyCodeSendClient smsVerifyCodeSendClient;

    @Autowired
    private LoginUserClient loginUserClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @GlobalTransactional
    public AjaxResult registerByPhone(SmsRegisterDto dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        String validateCode = dto.getValidateCode();

        // 1 校验：空校验和用户是否已注册校验
        List<User> users = userMapper.selectList(new EntityWrapper<User>().eq("phone", phone));
        Assert.listIsEmpty(users, ResponseEnum.CODE_USER_EXISTED);

        // 2 验证码比对
        String value = (String) redisTemplate.opsForValue().get("register_sms_code_" + phone);
        String code = value.substring(0, 6);

        if (!code.equals(validateCode)) {
            return AjaxResult.me().setSuccess(false).setMessage("验证码输入错误！");
        }

        // 3 注册
        // 3.1 保存用户登录信息
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(UUID.randomUUID().toString());
        loginUser.setPassword(password);
        loginUser.setTel(phone);
        loginUser.setType(1);
        AjaxResult result = loginUserClient.addOrUpdate(loginUser);
        if (!result.isSuccess()) {
            return result;
        }
//        Long loginUserId = Long.valueOf(result.getResultObj().toString());

        //2.2 保存用户信息
        User user = new User();
        user.setCreateTime(new Date());
        user.setPhone(phone);
        user.setPassword(password);
        user.setBitState(1L);
        user.setSecLevel(1);
//        user.setLoginId(loginUserId);
        user.setUsername(loginUser.getUsername());
        userMapper.insert(user);
        return AjaxResult.me().setSuccess(true).setMessage("注册成功！");
    }
}
